/*
import java.util.PriorityQueue;

*/
/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:
 * Date: 2025-04-20
 * Time: 20:13
 *//*


//1.实现一个类，表示一个任务，任务包括任务名和时间
class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable task;
    private long time;

    public MyTimerTask(Runnable task, long time){
        this.task = task;
        this.time = time;
    }


    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time - o.time);
    }

    public long getTime(){
        return time;
    }

    public void run(){
        task.run();
    }
}


//自己实现一个定时器
class MyTimer{

    //2.使用集合类管理多个任务
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();

    private Object locker = new Object();

    //3.创建schedule方法
    public void schedule(Runnable task, long delay){
        synchronized(locker){
            MyTimerTask timerTask = new MyTimerTask(task, System.currentTimeMillis() + delay);
            queue.offer(timerTask);
            locker.notify();
        }
    }

    //4.创建一个线程，负责执行队列中的任务
    public MyTimer(){
        Thread t = new Thread(() -> {
           try{
               while(true){
                   synchronized(locker){
                       while(queue.isEmpty()){
                           locker.wait();
                       }
                       MyTimerTask task = queue.peek();
                       if(System.currentTimeMillis() < task.getTime()) {
                           locker.wait(task.getTime() - System.currentTimeMillis());
                       }else{
                           task.run();
                           queue.poll();
                       }
                   }
               }
           }catch (InterruptedException e){
               e.printStackTrace();
           }
        });
        t.start();
    }
}

public class demo6 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        },3000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2000");
            }
        },2000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1000");
            }
        },1000);
    }
}
*/
